package com.shyroke.daydayzhuanweb.controller;

import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuanapi.dto.CommentDto;
import com.shyroke.daydayzhuanapi.dto.UserMain;
import com.shyroke.daydayzhuanapi.entity.CommentEntity;
import com.shyroke.daydayzhuanapi.entity.ProjectEntity;
import com.shyroke.daydayzhuanapi.entity.RoleEntity;
import com.shyroke.daydayzhuanapi.entity.UserEntity;
import com.shyroke.daydayzhuandao.respository.CommentRepository;
import com.shyroke.daydayzhuandao.respository.ProjectRepository;
import com.shyroke.daydayzhuandao.respository.UserRepository;
import com.shyroke.daydayzhuansvc.service.IProjectService;
import com.shyroke.daydayzhuansvc.service.MailService;
import com.shyroke.daydayzhuansvc.service.impl.CommentService;
import com.shyroke.daydayzhuansvc.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 类名 ：文章评论controller
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/12/28 12:38
 */
@Controller
@RequestMapping(value = "admin/comment")
public class CommentController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CommentService commentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MailService mailService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CommentRepository commentRepository;

    /**
     * 跳转到评论管理页面
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView list(ModelAndView model,HttpSession session){
        UserMain user = (UserMain)session.getAttribute("user");
        Set<RoleEntity> roleList = userRepository.findByName(user.getName()).getRoleList();
        boolean isAdmin = UserUtils.isAdmin2(roleList);
        model.addObject("isAdmin",isAdmin);
        model.setViewName("admin/comment/list");
        return model;
    }

    @RequestMapping(value = "getTableDate")
    @ResponseBody
    public TabelData<CommentDto> getTableDate(Page page, String title, HttpSession session){
        UserMain user = (UserMain)session.getAttribute("user");
        return commentService.getTableDate(page,title,user);
    }

    @RequestMapping(value = "opt")
    @ResponseBody
    @PermissionAnnotation(permissionName = "comment:update")
    public R opt(Integer id,String action){
        if(id == null || StringUtils.isEmpty(action)){
            return R.error("id或者action不能为空！");
        }

        CommentEntity comment = commentService.getCommentById(id);
        if(comment == null){
            return R.error("没有找到该评论！");
        }

        if("del".equals(action)){
            //删除
            commentService.del(id);
        }else if("pass".equals(action)){
            //审核通过
            comment.setStatus(1);
            commentRepository.save(comment);

            //阅读量+1
            ProjectEntity project = projectService.getProjectById(comment.getArticleId());
            project.setCommentMount(project.getCommentMount()+1);
            projectRepository.save(project);

            if(comment.getReplyForId() != 0){
                //邮件提醒用户
                CommentEntity replyComment = commentService.getCommentById(comment.getReplyForId());
                ProjectEntity commentProject = projectService.getProjectById(comment.getArticleId());
                String projectUrl = "https://www.daydayzhuan.com/article/"+commentProject.getId();
                mailService.sendNewReply(replyComment.getEmail(),projectUrl);
            }else{
                //没有回复ID则说明是直接回复文章作者
                Optional<ProjectEntity> optionalProject = projectRepository.findById(comment.getArticleId());
                if (optionalProject.isPresent()) {
                    ProjectEntity project1 = optionalProject.get();
                    Optional<UserEntity> optionalUser = userRepository.findById(project1.getCreateId());
                    if(optionalUser.isPresent()){
                        UserEntity user = optionalUser.get();
                        String projectUrl = "https://www.daydayzhuan.com/article/"+project1.getId();
                        mailService.sendNewReply(user.getEmail(),projectUrl);
                    }
                }
            }

            //删除评论缓存
            redisTemplate.delete(RedisKeyPrefix.COMMENTLIST);

        }else if("fail".equals(action)){
            //审核失败
            comment.setStatus(2);
            commentRepository.save(comment);
        }else{
            return R.error("action值错误！");
        }

        return R.ok("操作成功！");

    }


    /**
     * 回复
     *
     * @return
     */
    @RequestMapping(value = "reply")
    @ResponseBody
    public R reply(Integer id,String content,HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        Set<RoleEntity> roleList = userRepository.findByName(user.getName()).getRoleList();
        boolean isAdmin = UserUtils.isAdmin2(roleList);
        if(StringUtils.isEmpty(content)){
            return R.error("评论内容不能为空");
        }

        CommentEntity comment = new CommentEntity();

        CommentEntity comment1 = commentService.getCommentById(id);
        if(comment1  == null){
            return R.error("评论文章为空！");
        }
        comment.setStatus(1);
        if(isAdmin){
            comment.setImage("/img/logo_2.jpg");
            comment.setUserName("天天线报网");
            comment.setEmail("qweyhj@qq.com");
        }else{
            comment.setImage("/img/user.png");
            comment.setUserName(user.getAuthor());
            comment.setEmail(user.getEmail());
        }
        comment.setCreateTime(new Date());
        comment.setUrl("https://www.daydayzhuan.com/");
        comment.setContent(content);

        //获取该评论的楼主
       if( comment1.getReplyForId() == 0){
           comment.setReplyForId(comment1.getId());
       }else{
           List<CommentEntity> commentList  = commentService.getCommentByProjectId(comment1.getArticleId());
           Integer replyParentId = this.getReplyParentId(comment1.getReplyForId(),commentList);
           comment.setReplyForId(replyParentId == null?0:replyParentId);
       }

        comment.setArticleId(comment1.getArticleId());
        comment.setReplyForName(comment1.getUserName());

        commentRepository.save(comment);
        redisTemplate.delete(RedisKeyPrefix.COMMENTLIST);

        return R.ok("保存成功");
    }


    private Integer getReplyParentId(Integer replyForId, List<CommentEntity> commentList) {

        Integer result = null;

        for(CommentEntity comment:commentList){
            if(comment.getId().equals(replyForId)){
                replyForId = comment.getReplyForId();
                result =  comment.getId();
            }
        }

        if(replyForId !=  0){
            result = getReplyParentId(replyForId,commentList);
        }


        return result;

    }

}
